package base

import (
	consts2 "MoSkeleton/config/consts"
	"MoSkeleton/global/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

var BaseDb *gorm.DB

type BaseService struct {
}

func (b *BaseService) GetDb(tx *gorm.DB) *gorm.DB {
	if tx != nil {
		return tx
	}
	return BaseDb
}

func (b *BaseService) DeleteByIds(tx *gorm.DB, model any, ids *[]string) (bool, error) {
	result := b.GetDb(tx).Where("id in (?)", *ids).Delete(model)
	return result.RowsAffected > 0, result.Error
}

func (b *BaseService) UpdateById(tx *gorm.DB, model any) (bool, error) {
	result := b.GetDb(tx).Updates(model)
	return result.RowsAffected > 0, result.Error
}

/*
开启查询的 data scope 准备
*/
func (b *BaseService) QueryDataScope(c *gin.Context, db *gorm.DB) *BaseService {
	db.Set(consts2.Gorm_Config_DataScope, consts2.U_YES)
	db.Set(consts2.Gorm_Config_OnlineUser, utils.GetOnlineUserFromGin(c))
	db.Set(consts2.Gorm_Config_DataScope_Count, 0)
	db.Set(consts2.Gorm_Config_MaxCount_PerReq, consts2.Gorm_MaxCount_PerReq_Def)
	return b
}

func (b *BaseService) SetDataScopeUserAlias(db *gorm.DB, alias string) *BaseService {
	b.SetDataScopeAlias(db, consts2.Gorm_Config_User_Alias, alias, consts2.Gorm_User_Alias_Default)
	return b
}

func (b *BaseService) SetDataScopeDeptAlias(db *gorm.DB, alias string) *BaseService {
	b.SetDataScopeAlias(db, consts2.Gorm_Config_Dept_Alias, alias, consts2.Gorm_Dept_Alias_Default)
	return b
}

func (b *BaseService) SetDataScopeAlias(db *gorm.DB, aliasKey, aliasValue, defValue string) *BaseService {
	if aliasValue == "" {
		db.Set(aliasKey, defValue)
	} else {
		db.Set(aliasKey, aliasValue)
	}
	return b
}
